# rice_management_project/views.py (or wherever home_view is)
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db.models import Sum, Count # Import Sum and Count
from django.db.models.functions import TruncMonth # To group by month
from planting_records.models import PlantingRecord # Import relevant model
from field_management.models import Field # May need Field for area
import json # To pass data safely to template
from collections import defaultdict # For easy aggregation

@login_required
def home_view(request):
    """
    Displays the dashboard/home page with charts.
    """
    user = request.user
    context = {'page_title': '仪表盘'}

    # --- Chart 1: Area Planted per Variety ---
    # Get planting records with valid field area for the user
    # We join Field to get the area. We group by variety name.
    # Note: This assumes one PlantingRecord means the whole field area is used for that variety in that record.
    # A more complex model might track area per planting.
    variety_area_data = PlantingRecord.objects.filter(
        owner=user,
        field__area__isnull=False # Ensure field has an area
    ).values(
        'rice_variety' # Group by variety
    ).annotate(
        total_area=Sum('field__area') # Sum the area of fields associated with this variety's plantings
    ).order_by('-total_area') # Order by largest area first

    # Prepare data for Chart.js Pie Chart
    variety_labels = [item['rice_variety'] for item in variety_area_data]
    variety_areas = [float(item['total_area']) for item in variety_area_data] # Ensure float for JS

    # Pass data as JSON to avoid issues with template tags in JS
    context['variety_area_labels_json'] = json.dumps(variety_labels)
    context['variety_area_data_json'] = json.dumps(variety_areas)


    # --- Chart 2: Plantings per Month ---
    # Group planting records by month/year
    plantings_per_month = PlantingRecord.objects.filter(
        owner=user
    ).annotate(
        month=TruncMonth('planting_date') # Truncate date to month
    ).values(
        'month' # Group by the truncated month
    ).annotate(
        count=Count('id') # Count records per month
    ).order_by('month') # Order chronologically

    # Prepare data for Chart.js Bar Chart
    month_labels = [item['month'].strftime('%Y-%m') for item in plantings_per_month] # Format date as YYYY-MM
    month_counts = [item['count'] for item in plantings_per_month]

    context['planting_month_labels_json'] = json.dumps(month_labels)
    context['planting_month_data_json'] = json.dumps(month_counts)

    # --- Add other context if needed ---
    context['total_fields'] = Field.objects.filter(owner=user).count()
    context['total_records'] = PlantingRecord.objects.filter(owner=user).count()


    return render(request, 'home.html', context)